package com.waner.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.waner.reggie.common.CustomException;
import com.waner.reggie.common.R;
import com.waner.reggie.dto.DishDto;
import com.waner.reggie.entity.Category;
import com.waner.reggie.entity.Dish;
import com.waner.reggie.entity.DishFlavor;
import com.waner.reggie.mapper.DishMapper;
import com.waner.reggie.service.CategoryService;
import com.waner.reggie.service.DishFlavorService;
import com.waner.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;


    /**
     * 新增菜品
     * @param dishDto
     */
    @Override
    public void saveWithFlavors(DishDto dishDto) {
        log.info("新增菜品....{},口味{}",dishDto);

        // 存储对应的对象
       this.save(dishDto);

       // 将菜品的id封装给flavor
       Long id = dishDto.getId();
       List<DishFlavor> flavors = dishDto.getFlavors();
       flavors = flavors.stream().map((dishFlavor) -> {
           dishFlavor.setDishId(id);
           return dishFlavor;
       }).collect(Collectors.toList());

       dishFlavorService.saveBatch(flavors);
    }

    /**
     * 菜品（返回需要所属的分类）的分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @Override
    public Page<DishDto> pageWithCategoryName(int page, int pageSize, String name) {
        // 使用MyBatisPlus框架提供的类进行分页查询
        Page<Dish> pageInfo = new Page<>(page,pageSize);
        Page<DishDto> pageDto = new Page<>();

        // 使用sort进行排序
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        // 如果关键字不为空，那么就增加关键字查询
        queryWrapper.like(!StringUtils.isEmpty(name),Dish::getName,name);
        // queryWrapper.orderByAsc(Dish::getSort);
        queryWrapper.orderByDesc(Dish::getUpdateTime);

        // 开始进行查询
        this.page(pageInfo,queryWrapper);

        // 进行对象中拷贝--处理其中的rcords列表中的对象
        BeanUtils.copyProperties(pageInfo,pageDto,"records");

        // 将record中的数据转化
        List<DishDto> dishDtos = null;
        List<Dish> dishList = pageInfo.getRecords();
        // 将集合中的对象信息进行拷贝和完善
        dishDtos = dishList.stream().map((item)-> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item,dishDto);
            Category category = categoryService.getById(item.getCategoryId());
            if(category != null) {
                dishDto.setCategoryName(category.getName());
            }
            return dishDto;
        }).collect(Collectors.toList());

        pageDto.setRecords(dishDtos);

        return pageDto;
    }

    /**
     * 修改菜品的信息和对应的口味信息
     * @param dishDto
     */
    @Override
    public void updateWithFlavors(DishDto dishDto) {
        // 根据dish_id删除所有的口味信息
        // 条件查询构造器
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId,dishDto.getId());
        // 进行删除
        dishFlavorService.remove(queryWrapper);

        // 修改菜品
        this.updateById(dishDto);

        // 新增口味操作
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors = flavors.stream().map((flavor)->{
            flavor.setDishId(dishDto.getId());
            return flavor;
        }).collect(Collectors.toList());

        dishFlavorService.saveBatch(flavors);

    }

    /**
     * 根据id查询菜品和菜品口味信息
     * @param id
     * @return
     */
    @Override
    public DishDto getDishByIdWithFlavor(Long id) {
        // 首先查询相关的菜品
        Dish dish = this.getById(id);

        // 获取相关的flavor
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId,id);
        List<DishFlavor> flavors = dishFlavorService.list(queryWrapper);

        // 进行拷贝和赋值
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(dish,dishDto);

        dishDto.setFlavors(flavors);
        return dishDto;
    }

    /**
     * 根据id批量删除菜品以及口味关联表中的数据
     * @param ids
     */
    @Override
    public void deleteWithFlavors(List<Long> ids) {
        // 首先判断菜品中是否存在起售中的菜品
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.eq(Dish::getStatus,1);
        dishLambdaQueryWrapper.in(Dish::getId,ids);

        if(this.count(dishLambdaQueryWrapper) > 0){
            throw new CustomException("存在起售中的菜品，无法删除菜品");
        }

        // 批量删除菜品
        this.removeByIds(ids);

        // delete from dish_flavor where dish_is in (ids)
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(DishFlavor::getDishId,ids);

        dishFlavorService.remove(queryWrapper);
    }

    @Override
    public List<DishDto> listByCategoryIdWithFlavors(Long categoryId) {
        // 构造条件查询器 select * from dish where category_id = ?
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Dish::getCategoryId,categoryId);
        queryWrapper.eq(Dish::getStatus,1);
        queryWrapper.orderByDesc(Dish::getUpdateTime);

        // 开始进行查询
        List<Dish> dishes = this.list(queryWrapper);

        // 补充查询  select * from dish_flavors where dish_id = ?
        List<DishDto> dishDtos = new LinkedList<>();

        // 根据每一个菜品查询对应的口味列表，然后加入到DTO中
        for(Dish dish:dishes){
            LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(DishFlavor::getDishId,dish.getId());
            DishDto dishDto = new DishDto();
            // 基本属性的赋值操作
            BeanUtils.copyProperties(dish,dishDto);
            dishDto.setFlavors(dishFlavorService.list(wrapper));
            dishDtos.add(dishDto);
        }
        return dishDtos;
    }
}
